﻿/*  Eleven Business Suite : Un ERP básico para pequeños empresarios.
 *  Copyright (C) 2011  Francis Bolaños Arias
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>;.
 */

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using ElevenGlobal;

namespace ElevenData
{
    public class Eliminar
    {

        #region Gerencia

        public static bool eliminarPaises(int IdPais)
        {
            DataTable dt = Consultar.ConsultarProvincias(IdPais);
            if (dt.Rows.Count == 0)
            {
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);
                SqlCommand comando = new SqlCommand("DELETE FROM [11PAISES] WHERE IdPais = @IdPais");
                SqlParameter param;
                param = comando.Parameters.Add("@IdPais", SqlDbType.Int);
                param.Value = IdPais;
                comando.Connection = conn;
                conn.Open();
                comando.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool eliminarProvincias(int IdProvincia)
        {
            DataTable dt = Consultar.ConsultarCantones(IdProvincia);
            if (dt.Rows.Count == 0)
            {
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);
                SqlCommand comando = new SqlCommand("DELETE FROM [11PROVINCIAS] WHERE IdProvincia = @IdProvincia");
                SqlParameter param;
                param = comando.Parameters.Add("@IdProvincia", SqlDbType.Int);
                param.Value = IdProvincia;
                comando.Connection = conn;
                conn.Open();
                comando.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool eliminarCantones(int IdCanton)
        {
            DataTable dt = Consultar.ConsultarDistritos(IdCanton);
            if (dt.Rows.Count == 0)
            {
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);
                SqlCommand comando = new SqlCommand("DELETE FROM [11CANTONES] WHERE IdCanton = @IdCanton");
                SqlParameter param;
                param = comando.Parameters.Add("@IdCanton", SqlDbType.Int);
                param.Value = IdCanton;
                comando.Connection = conn;
                conn.Open();
                comando.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool eliminarDistritos(int IdDistrito)
        {
            //Falta validar clientes y rutas y, algún otro que dependa de este dato.
            DataTable dt = Consultar.ConsultarProveedoresXDistrito(IdDistrito);
            if (dt.Rows.Count == 0)
            {
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);
                SqlCommand comando = new SqlCommand("DELETE FROM [11DISTRITOS] WHERE IdDistrito = @IdDistrito");
                SqlParameter param;
                param = comando.Parameters.Add("@IdDistrito", SqlDbType.Int);
                param.Value = IdDistrito;
                comando.Connection = conn;
                conn.Open();
                comando.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region Inventario

        public static bool eliminarProveedores(int IdProveedor)
        {
            //Restringir proveedor no este en orden compra
            //DataTable dt = 
            //if (dt.Rows.Count == 0)
            //{
            SqlConnection conn = new SqlConnection(Configuracion.connectionString);
            SqlCommand comando = new SqlCommand("DELETE FROM [11PROVEEDORES] WHERE IdProveedor = @IdProveedor");
            SqlParameter param;
            param = comando.Parameters.Add("@IdProveedor", SqlDbType.Int);
            param.Value = IdProveedor;
            comando.Connection = conn;
            conn.Open();
            comando.ExecuteNonQuery();
            conn.Close();
            return true;
            //}
            //else
            //{
            //    Cache.ErrorActual = "No se puede eliminar el proveedor porque tiene ordenes de compra asociadas.";
            //    return false;
            //}
        }

        public static bool eliminarCategorias(int IdCategoria)
        {
            DataTable dt = Consultar.ConsultarSubcategorias(IdCategoria);
            if (dt.Rows.Count == 0)
            {
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);
                SqlCommand comando = new SqlCommand("DELETE FROM [11PRODCAT] WHERE IdCategoria = @IdCategoria");
                SqlParameter param;
                param = comando.Parameters.Add("@IdCategoria", SqlDbType.Int);
                param.Value = IdCategoria;
                comando.Connection = conn;
                conn.Open();
                comando.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool eliminarSubcategorias(int IdSubcategoria)
        {
            DataTable dt = Consultar.ConsultarProductosXSubcategoria(IdSubcategoria);
            if (dt.Rows.Count == 0)
            {
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);
                SqlCommand comando = new SqlCommand("DELETE FROM [11PRODSUBCAT] WHERE IdSubcategoria = @IdSubcategoria");
                SqlParameter param;
                param = comando.Parameters.Add("@IdSubcategoria", SqlDbType.Int);
                param.Value = IdSubcategoria;
                comando.Connection = conn;
                conn.Open();
                comando.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool eliminarProductos(int IdProducto)
        {
            DataTable dt = Consultar.ConsultarDTOrdenCompraXProducto(IdProducto);
            if (dt.Rows.Count == 0)
            {
                SqlTransaction tran;
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);

                SqlCommand comando = new SqlCommand("DELETE FROM [11PRODUCTOS] WHERE IdProducto = @IdProducto");
                SqlParameter param;
                param = comando.Parameters.Add("@IdProducto", SqlDbType.Int);
                param.Value = IdProducto;
                comando.Connection = conn;
                conn.Open();
                tran = conn.BeginTransaction();
                try
                {
                    comando.Transaction = tran;
                    comando.ExecuteNonQuery();
                    //try
                    //{
                    //    DataTable dt = Consultar.consultarPrecioVentaProductos(IdProducto);
                    //    if (dt.Rows.Count != 0)
                    //    {
                    //        eliminarPrecioVentaProductos(IdProducto, conn, tran);
                    //    }
                    //}
                    //catch(Exception) { }
                    tran.Commit();
                    conn.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    Cache.ErrorActual = ex.Message;
                    tran.Rollback();
                    conn.Close();
                    return false;
                }
            }
            else
            {
                Cache.ErrorActual = "Este producto no puede eliminarse porque ya está incluido en órdenes de compra o facturas.";
                return false;
            }
        }

        public static bool eliminarOrdenCompra(int IdOrdenCompra)
        {
            //Validar que no este asociada a una entrega.

            //Trasacción. Debe eliminar DetalleOrdenCompra
            //y restar inventario (cant cada producto) si es necesario.
            SqlTransaction tran;
            SqlConnection conn = new SqlConnection(Configuracion.connectionString);
            SqlCommand comando = new SqlCommand("DELETE FROM [11ORDENCOMPRA] WHERE IdOrdenCompra = @IdOrdenCompra");
            SqlParameter param;
            param = comando.Parameters.Add("IdOrdenCompra", SqlDbType.Int);
            param.Value = IdOrdenCompra;
            comando.Connection = conn;
            conn.Open();
            tran = conn.BeginTransaction();
            try
            {
                //Buscar si ya fue entregada o no.
                DataTable dt = Consultar.ConsultarOrdenCompraXID(IdOrdenCompra);
                DataRow dr3 = dt.Rows[0];
                //11VSTORDENCOMPRA.Entregado
                int entregado = int.Parse(dr3[7].ToString());
                if (entregado == 1)
                {
                    //Modificar Cantidades
                    dt = Consultar.ConsultarDTOrdenCompra(IdOrdenCompra);
                    foreach (DataRow dr in dt.Rows)
                    {
                        //11VSTDTORDENCOMPRA.IdProducto
                        DataTable dt2 = Consultar.ConsultarProductoXID(int.Parse(dr[1].ToString()), conn, tran);
                        //1ra Fila
                        DataRow dr2 = dt2.Rows[0];
                        //11PRODUCTOS.Cantidad - 11VSTDTORDENCOMPRA.Cantidad
                        int Cantidad = int.Parse(dr2["Cantidad"].ToString()) - int.Parse(dr["Cantidad"].ToString());
                        //11VSTDTORDENCOMPRA.IdProducto
                        Modificar.modificarProductoCantidad(int.Parse(dr[1].ToString()), Cantidad, conn, tran);
                    }
                }

                //Eliminar Detalles
                eliminarDTOrdenCompra(IdOrdenCompra, conn, tran);

                //Eliminar Orden
                comando.Transaction = tran;
                comando.ExecuteNonQuery();

                tran.Commit();
                conn.Close();
                return true;
            }
            catch (SqlException ex)
            {
                Cache.ErrorActual = ex.Message;
                tran.Rollback();
                conn.Close();
                return false;
            }
        }

        public static bool eliminarDTOrdenCompra(int IdOrdenCompra, SqlConnection conn, SqlTransaction tran)
        {
            SqlCommand comando = new SqlCommand("DELETE FROM [11DTORDENCOMPRA] WHERE IdOrdenCompra = @IdOrdenCompra");
            SqlParameter param;
            param = comando.Parameters.Add("@IdOrdenCompra", SqlDbType.Int);
            param.Value = IdOrdenCompra;
            comando.Connection = conn;
            comando.Transaction = tran;
            comando.ExecuteNonQuery();
            return true;
        }

        public static bool eliminarPrecioVenta(int IdPrecioVenta)
        {
            try
            {
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);
                SqlCommand comando = new SqlCommand("DELETE FROM [11PRECIOVENTAPROD] WHERE IdPrecioVenta = @IdPrecioVenta");
                SqlParameter param;
                param = comando.Parameters.Add("@IdPrecioVenta", SqlDbType.Int);
                param.Value = IdPrecioVenta;
                comando.Connection = conn;
                conn.Open();
                comando.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            catch (Exception ex) {
                Cache.ErrorActual = ex.Message;
                return false;
            }
        }

        public static bool eliminarPerdida(int IdPerdida, int IdProducto, int Cantidad)
        {
            SqlTransaction tran;
            SqlConnection conn = new SqlConnection(Configuracion.connectionString);
            SqlCommand comando = new SqlCommand("DELETE FROM [11PERDIDAS] WHERE IdPerdida = @IdPerdida");
            SqlParameter param;
            param = comando.Parameters.Add("@IdPerdida", SqlDbType.Int);
            param.Value = IdPerdida;
            comando.Connection = conn;
            conn.Open();
            tran = conn.BeginTransaction(IsolationLevel.ReadUncommitted);
            try
            {
                comando.Transaction = tran;
                comando.ExecuteNonQuery();
                //Modificar Cantidad
                DataTable dt = Consultar.ConsultarProductoXID(IdProducto, conn, tran);
                DataRow dr2 = dt.Rows[0];
                int CantidadNueva = int.Parse(dr2["Cantidad"].ToString()) + Cantidad;
                Modificar.modificarProductoCantidad(IdProducto, CantidadNueva, conn, tran);

                tran.Commit();
                conn.Close();
                return true;
            }
            catch (Exception ex)
            {
                Cache.ErrorActual = ex.Message;
                tran.Rollback();
                conn.Close();
                return false;
            }
        }

        #endregion

        #region Punto de Venta

        public static bool eliminarClientes(int IdCliente)
        {
            DataTable dt = Consultar.validarFacturaCliente(IdCliente);
            if (dt.Rows.Count == 0)
            {
                SqlConnection conn = new SqlConnection(Configuracion.connectionString);
                SqlCommand comando = new SqlCommand("DELETE FROM [11CLIENTES] WHERE IdCliente = @IdCliente");
                SqlParameter param;
                param = comando.Parameters.Add("@IdCliente", SqlDbType.Int);
                param.Value = IdCliente;
                comando.Connection = conn;
                conn.Open();
                comando.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region Clientes

        public static bool eliminarConsultas(int IdConsulta)
        {
            SqlConnection conn = new SqlConnection(Configuracion.connectionString);
            SqlCommand comando = new SqlCommand("DELETE FROM [11CONSULTAS] WHERE IdConsulta = @IdConsulta");
            SqlParameter param;
            param = comando.Parameters.Add("@IdConsulta", SqlDbType.Int);
            param.Value = IdConsulta;
            comando.Connection = conn;
            conn.Open();
            comando.ExecuteNonQuery();
            conn.Close();
            return true;
        }

        #endregion

    }
}
